<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.id"
        placeholder="产品编号"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        Search
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        Export
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="产品编号" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品名称" min-width="100" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品期限" align="center" width="50px">
        <template slot-scope="{ row }">
          <span>{{ row.term }}</span>
        </template>
      </el-table-column>

      <el-table-column label="年利化率" width="50px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.annualProfitRate }}</span>
        </template>
      </el-table-column>

      <el-table-column label="起存金额" width="80px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.initialDepositAmount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="递增金额" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.incrementalAmount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="单人限额" width="80" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.limitAmount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="单日限额" width="80" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.dayLimitAmount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="风险等级" width="50" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.riskLevel }}</span>
        </template>
      </el-table-column>

      <el-table-column label="结息方式" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.interestSettlementMethod }}</span>
        </template>
      </el-table-column>

      <el-table-column label="限制区域" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.limitArea }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品原子服务编号" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.service }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品库存" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.allowance }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            Delete
          </el-button>
          <el-button type="primary" size="mini" @click="updateAtomic(row)">
            Layout
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog title="产品属性配置" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="top"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="产品编号" prop="id">
          <el-input v-model="temp.id" />
        </el-form-item>

        <el-form-item label="产品名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-form-item label="产品期限" prop="term">
          <el-select v-model="temp.term" placeholder="选择产品期限">
            <el-option
              v-for="item in productTerm"
              :key="item"
              :label="item + '月'"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="年利化率（%）" prop="annualProfitRate">
          <el-input v-model="temp.annualProfitRate" />
        </el-form-item>

        <el-form-item label="起存金额（元）" prop="initialDepositAmount">
          <el-input v-model="temp.initialDepositAmount" />
        </el-form-item>

        <el-form-item label="递增金额（元）" prop="incrementalAmount">
          <el-input v-model="temp.incrementalAmount" />
        </el-form-item>

        <el-form-item label="单人限额（元）" prop="limitAmount">
          <el-input v-model="temp.limitAmount" />
        </el-form-item>

        <el-form-item label="单日限额（元）" prop="dayLimitAmount">
          <el-input v-model="temp.dayLimitAmount" />
        </el-form-item>

        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="temp.riskLevel" placeholder="请选择产品风险等级">
            <el-option
              v-for="(item, index) in riskLevelList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="结息方式" prop="interestSettlementMethod">
          <el-input v-model="temp.interestSettlementMethod" />
        </el-form-item>

        <el-form-item label="限制区域" prop="limitArea">
          <el-input v-model="temp.limitArea" />
        </el-form-item>

        <el-form-item label="产品剩余购买数量" prop="allowance">
          <el-input v-model="temp.allowance" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateData()"> Confirm </el-button>
        <el-button @click="dialogFormVisible = false"> Cancel </el-button>
      </div>
    </el-dialog>

    <el-dialog title="产品服务配置" :visible.sync="isShowAtomic">
      <div
        class="components-container"
        style="width: 700px; margin-left: 40px; height: 350px"
      >
        <div class="editor-container">
          <div class="dndList">
            <div style="width: 48%" class="dndList-list">
              <h3>已选服务</h3>
              <draggable
                :set-data="setData"
                :list="owned"
                group="article"
                class="dragArea"
              >
                <div
                  v-for="(v, index) in owned"
                  :key="index"
                  class="list-complete-item"
                >
                  <div class="list-complete-item-handle">
                    {{ v }}
                  </div>
                  <div style="position: absolute; right: 0px">
                    <span
                      style="float: right; margin-top: -20px; margin-right: 5px"
                      @click="deleteEle(v)"
                    >
                      <i style="color: #ff4949" class="el-icon-delete" />
                    </span>
                  </div>
                </div>
              </draggable>
            </div>

            <div style="width: 48%" class="dndList-list">
              <h3>可选服务</h3>
              <draggable :list="notOwned" group="article" class="dragArea">
                <div
                  v-for="(v, index) in notOwned"
                  :key="index"
                  class="list-complete-item"
                >
                  <div class="list-complete-item-handle2" @click="pushEle(v)">
                    {{ v }}
                  </div>
                </div>
              </draggable>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateAtomicServices()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  getProducts,
  updateProduct,
  deleteProduct,
  searchPro,
  addService,
} from "@/api/product";
import { getAtomic } from "@/api/atomic";

export default {
  name: "ProductTable",
  components: { Pagination, draggable },
  directives: { waves },
  data() {
    return {
      isShowAtomic: false,
      owned: null,
      productId: "",
      notOwned: null,
      atomicMap: null,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        id: "",
      },
      temp: {
        id: "", // 产品编号
        name: "", // 产品名称
        term: 0, // 产品期限
        annualProfitRate: 0, // 年利化率
        initialDepositAmount: 0, // 起存金额
        incrementalAmount: 0, // 递增金额
        limitAmount: 0, // 单人限额
        dayLimitAmount: 0, // 单日限额
        riskLevel: "", // 风险等级
        interestSettlementMethod: "", // 结息方式
        limitArea: "",
        service: "",
        allowance: 0,
      },
      dialogFormVisible: false,
      downloadLoading: false,
      productTerm: [3, 6, 12, 24, 36, 48, 60, 120],
      riskLevelList: ["低风险", "中等风险", "高风险"],
      rules: {
        id: [{ required: true, message: "请输入产品编号", trigger: "blur" }],
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        term: [
          { required: true, message: "请选择产品期限", trigger: "change" },
        ],
        annualProfitRate: [
          { required: true, message: "请输入金额", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isFinite(value) && value >= 0) {
                callback();
              } else {
                callback(new Error("请输入不小于0的数字"));
              }
            },
            trigger: "blur",
            transform(value) {
              return Number(value);
            },
          },
        ],
        initialDepositAmount: [
          { required: true, message: "请输入金额", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isFinite(value) && value >= 0) {
                callback();
              } else {
                callback(new Error("请输入不小于0的数字"));
              }
            },
            trigger: "blur",
            transform(value) {
              return Number(value);
            },
          },
        ],
        incrementalAmount: [
          { required: true, message: "请输入金额", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isFinite(value) && value >= 0) {
                callback();
              } else {
                callback(new Error("请输入不小于0的数字"));
              }
            },
            trigger: "blur",
            transform(value) {
              return Number(value);
            },
          },
        ],
        limitAmount: [
          { required: true, message: "请输入金额", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isFinite(value) && value >= 0) {
                callback();
              } else {
                callback(new Error("请输入不小于0的数字"));
              }
            },
            trigger: "blur",
            transform(value) {
              return Number(value);
            },
          },
        ],
        dayLimitAmount: [
          { required: true, message: "请输入金额", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isFinite(value) && value >= 0) {
                callback();
              } else {
                callback(new Error("请输入不小于0的数字"));
              }
            },
            trigger: "blur",
            transform(value) {
              return Number(value);
            },
          },
        ],
        riskLevel: [
          { required: true, message: "请选择风险等级", trigger: "change" },
        ],
        limitArea: [
          {
            required: true,
            message: "请输入限定区域",
            trigger: "change",
          },
        ],
        allowance: [
          { required: true, message: "请输入库存", trigger: "blur" },
          {
            validator(rule, value, callback) {
              if (Number.isFinite(value) && value >= 0) {
                callback();
              } else {
                callback(new Error("请输入不小于0的数字"));
              }
            },
            trigger: "blur",
            transform(value) {
              return Number(value);
            },
          },
        ],
        interestSettlementMethod: [
          { required: true, message: "请输入结息方式", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      getProducts().then((response) => {
        this.list = response.data;
        this.total = response.data.length;
        setTimeout(() => {
          this.listLoading = false;
        }, 1 * 1000);
      });

      getAtomic().then((res) => {
        //将所有的原子服务根据其id：name组成map
        this.atomicMap = res.data.reduce((pre, acc) => {
          pre[acc.id] = acc.name;
          return pre;
        }, {});
      });
    },
    searchProduct() {
      this.listLoading = true;
      searchPro(this.listQuery.id).then((res) => {
        if (res.data === null) {
          this.list = [];
          this.total = 0;
        } else {
          this.list = res.data;
          this.total = 1;
        }
        this.listQuery.id = "";
        setTimeout(() => {
          this.listLoading = false;
        }, 1 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.searchProduct();
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          updateProduct(tempData).then((res) => {
            const index = this.list.findIndex((v) => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.total = this.list.length;
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: res.msg,
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      deleteProduct(row.id).then((res) => {
        this.$notify({
          title: "Success",
          message: res.msg,
          type: "success",
          duration: 2000,
        });
        this.list.splice(index, 1);
        this.total = this.list.length;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "产品名称",
          "产品期限",
          "年利化率",
          "风险等级",
          "结息方式",
        ];
        const filterVal = [
          "name",
          "term",
          "annualProfitRate",
          "riskLevel",
          "interestSettlementMethod",
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "产品信息列表",
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    updateAtomic(row) {
      this.productId = row.id;
      //将原子服务字符串切分
      let serviceIds = row.service.split(",");
      let selectable = ["1", "2", "3", "4", "5", "6", "10"].filter((v) => {
        if (!serviceIds.includes(v)) return v;
      });
      this.notOwned = this.addServiceName(selectable);
      this.owned = this.addServiceName(serviceIds);
      this.isShowAtomic = true;
    },
    addServiceName(arr) {
      let tem = [];
      for (let i = 0; i < arr.length; i++) {
        tem.push(this.atomicMap[arr[i]]);
      }
      return tem;
    },
    updateAtomicServices() {
      let arr = [];
      let atomicService = {};
      atomicService.id = this.productId;
      let findKey = (obj, value, compare = (a, b) => a === b) => {
        return Object.keys(obj).find((k) => compare(obj[k], value));
      };

      if (this.owned === []) {
        atomicService.service = null;
        arr.push('1');
        arr.push('10');
        console.log("被执行");
      } else {
        for (var s of this.owned) {
          arr.push(findKey(this.atomicMap, s));
        }
        let arr2 = arr.slice(1, arr.length - 1);
        atomicService.service = arr2.join(",");
      }

      addService(atomicService).then((res) => {
        this.$notify({
          title: "Success",
          message: res.msg,
          type: "success",
          duration: 2000,
        });
        this.owned = [];
        this.notOwned = [];
        const index = this.list.findIndex((v) => v.id === this.productId);
        const temData = Object.assign({}, this.list[index])
        temData.service = arr.join(',');
        this.list.splice(index,1,temData);
        this.isShowAtomic = false;
      });
    },
    isNotInList1(v) {
      return this.owned.every((k) => v !== k);
    },
    isNotInList2(v) {
      return this.notOwned.every((k) => v !== k);
    },
    deleteEle(ele) {
      for (const item of this.owned) {
        if (item === ele) {
          const index = this.owned.indexOf(item);
          this.owned.splice(index, 1);
          break;
        }
      }
      if (this.isNotInList2(ele)) {
        this.notOwned.unshift(ele);
      }
    },
    pushEle(ele) {
      for (const item of this.notOwned) {
        if (item === ele) {
          const index = this.notOwned.indexOf(item);
          this.notOwned.splice(index, 1);
          break;
        }
      }
      if (this.isNotInList1(ele)) {
        this.owned.push(ele);
      }
    },
    setData(dataTransfer) {
      dataTransfer.setData("Text", "");
    },
  },
};
</script>

<style lang="scss" scoped>
.dndList {
  background: #fff;
  padding-bottom: 40px;
  &:after {
    content: "";
    display: table;
    clear: both;
  }
  .dndList-list {
    float: left;
    padding-bottom: 30px;
    &:first-of-type {
      margin-right: 2%;
    }
    .dragArea {
      margin-top: 15px;
      min-height: 50px;
      padding-bottom: 30px;
    }
  }
}

.list-complete-item {
  cursor: pointer;
  position: relative;
  font-size: 14px;
  padding: 5px 12px;
  margin-top: 4px;
  border: 1px solid #bfcbd9;
  transition: all 1s;
}

.list-complete-item-handle {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 50px;
}

.list-complete-item-handle2 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 20px;
}

.list-complete-item.sortable-chosen {
  background: #4ab7bd;
}

.list-complete-item.sortable-ghost {
  background: #30b08f;
}

.list-complete-enter,
.list-complete-leave-active {
  opacity: 0;
}
</style>

